import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormlyFormOptions } from '@ngx-formly/core';
import { ApesModalRef } from '@shared/apes/modal';
import { Subscription } from 'rxjs';
import { SubjectService } from '@core/services/events/subject.service';
import { map, mergeMap } from 'rxjs/operators';
import { Observable } from 'rxjs/index';
import { deepClone, exists, getJson, missing } from '../../utils/utils';
import { ApiService } from '@core/services/http/api.service';
import { FormService } from '@core/services/form.service';
import { ActivatedRoute } from '@angular/router';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { ButtonService } from '@core/services/button.service';
// import { deepClone, missing } from '../../utils/utils';
// import { ExpressionService } from '@core/services/expression/ExpressionService';

@Component({
  selector: 'apes-input-form',
  templateUrl: './apes-input-form.component.html',
})
export class ApesInputFormComponent implements OnInit {
  form: FormGroup;
  resultData: any = {};
  /**上下文环境变量**/
  ctx: any = {};

  /**用户信息**/
  user: any;

  /**订阅主题**/
  subjects = {};
  private change$: Subscription;
  tableValid = {};

  /**数据刷新Api**/
  findOneApi: string;


  fields = [];
  formMetadata = [];
  options: FormlyFormOptions = {};

  params: any;

  isLoading: boolean = false;

  // 用于判断弹框归属
  compileComponent: boolean = true;

  // /**数据刷新Api**/
  // findOneApi: string;

  constructor(
    protected route: ActivatedRoute,
    private modal: ApesModalRef,
    protected subject: SubjectService,
    protected apiService: ApiService,
    private formService: FormService,
    protected expressionService: ExpressionService,
    public buttonService: ButtonService,
  ) {
  }

  ngOnInit() {
    this.form = new FormGroup({});
    this.params = deepClone(this.modal['apesComponentParams']);
    // this.formMetadata = params.sheet;

    let id = this.modal['apesComponentParams'].id;
    this.initContext();


    let formId;
    if (this.params.hasOwnProperty('formId')) {
      formId = this.params.formId;
    } else {
      formId = this.params.api;
    }

    if (formId) {
      this.getFormMetadata(formId);
    } else {
      let metadata = this.params.sheet
      this.formService.extFormMetadata(metadata, this.ctx, this.subject, this.tableValid);
      this.formMetadata = metadata;
      if (this.params.hasOwnProperty('global')) {
        this.interceptEventListener(this.params.global.events);
        if (this.params.global.hasOwnProperty('api')) this.findOneApi = this.params.global.api;
      }
    }

    // setTimeout(()=>{
    if (this.params.hasOwnProperty('conditionModel')) {
      if (this.params.conditionModel.hasOwnProperty('node')) {
        this.refresh(this.params.conditionModel['node']);
        this.ctx.model = this.resultData;
      }
      // else {
      this.ctx.data = this.params.conditionModel;
      // }
    }
    // },3000);

    this.subject.subscribe(this.ctx, this.subject.event_form_load, data => {
      this.subject.publish(this.ctx, this.subject.event_form_button, { ctx: this.ctx, action: '' });
    });

    /** 页面按钮功能事件 **/
    this.subject.subscribe(this.ctx, this.subject.event_button, data => {
      this.buttonService.clickButton(data);
    });
  }

  /**
   * 功能：初始化上下文环境变量
   */
  private initContext() {
    let oldModel = deepClone(this.resultData);
    this.clearValue(this.resultData);
    this.form.reset({});
    // this.clearValue(this.searchModel);
    // this.searchForm.reset({});
    this.clearValue(this.ctx);
    // this.ctx.user = this.user;
    this.ctx.model = this.resultData;
    // this.setStates('new');
    this.ctx.form = this.form;
    this.ctx.subjects = this.subjects;
    this.clearValue(this.tableValid);
    this.ctx.valid = true;
    this.ctx.states = 'submit';
    this.options.formState = this.ctx;
    // this.ctx.searchService = this.searchService;
    // // 动态表单配置
    if (this.formMetadata && this.formMetadata.length > 0) {
      this.ctx.$formMetadata = this.formMetadata;
    }
    this.ctx.oldModel = oldModel;
    /**表格数据刷新**/
    this.subject.publish(this.ctx, this.subject.event_form_refresh, {});
  }

  /**
   * 功能：表单数据刷新
   * @param data
   */
  private refresh(data, resetStates = true) {

    this.clearValue(this.resultData);
    for (let key in data) {
      this.resultData[key] = data[key];
    }
    this.form.reset(data);
    this.subject.publish(this.ctx, this.subject.event_form_refresh, data);
  }

  /**
   * 功能：获取表单元数据
   */
  private getFormMetadata(formId) {

    this.getFormMetadataApi(formId).pipe(
      map((body) => {
        return body;
      }),
      // mergeMap(
      //   // data => this.getSearchFormMetadata(data)
      // ),
    ).subscribe((body) => {
      // this.searchFormViewType = body.searchFormViewType || 'dialog';
      // this.searchFormId = body.searchFormId;
      // this.searchFormMetadata = body.searchFormMetadata;
      // this.direction = body.direction || 'horizontal';
      // this.direction = body.direction || 'vertical';

      let metadata = body.sheet;
      this.formService.extFormMetadata(metadata, this.ctx, this.subject, this.tableValid);
      this.formMetadata = this.formMetadata.concat(metadata);

      this.ctx.$formMetadata = this.formMetadata;

      // this.change$ = <any> this.menuService.change.subscribe(res => {
      //   if (body.header.buttonbar != null) {
      //     this.auth(body.header.buttonbar);
      //     this.setBtnVisible();
      //   }
      //   this.cd.detectChanges();
      // });
      // if (body.header.statusbar != null) {
      //   this.statusBar = body.header.statusbar;
      // }
      //
      if (body.global) {
        this.interceptEventListener(body.global.events);
        if (body.global.api) this.findOneApi = body.global.api;
      }
      //
      // if (this.formService.formData.hasOwnProperty("key")){
      //   this.executeTask(this.formService.formData['key']);
      // }
      this.subject.publish(this.ctx, this.subject.event_form_refresh, this.ctx);
    });
  }

  /**
   * 功能：注册事件监听器
   * @param {string} topic
   */
  interceptEventListener(events: any[]) {
    if (missing(events)) return;
    events.forEach(em => {
      em.type.split(',').forEach(type => {
        /**订阅事件**/
        this.subject.subscribe(this.ctx, type, data => {
          this.expressionService.evaluate(em.callback, {
            context: this.ctx,
            form: this.form,
            model: this.resultData,
            data: data,
          }, true);
        });
      });
    });
  }

  private getFormMetadataApi(formId: string): Observable<any> {
    return this.apiService.post('form.get', { 'body': getJson({ id: formId }) }).pipe(map(
      (body) => {
        if (body) {
          return body;
        }
      }));
  }

  private clearValue(object: any) {
    for (let key in object) {
      delete object[key];
    }
  }

  destroyModal(): void {
    this.modal.destroy(this.resultData);
  }

}
